<?php

namespace App\Http\Model;


use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

/**
 * 用房间钱包, 此处设计没有遵循封闭原则, 有时间要优化, 整合到 FinanceWealth
 * Class FinanceRoomWallet
 * @package App\Http\Model
 */
class FinanceRoomWallet extends Base
{
    protected $table = 'finance_room_wallet';

    private $redis_cache_finance_user_wallet = "CACHE:FINANCE:USER:WALLET";
    private $redis_cache_finance_room_wallet = "CACHE:FINANCE:ROOM:WALLET";
    
    public $timestamps = false;
    public function __construct(array $attributes = [])
    {
        parent::__construct($this->table, $attributes);
    }

    /**
     * 初始化房间财富值
     * @param $room_id
     * @return bool
     */
    public function add_wallet($room_id){
        $data = [
            'room_id' => $room_id
        ];
        $result = DB::table($this->table)->insertGetId($data);
        return $result;
    }


    /**
     * 获取房间财富值
     * @param $room_id
     * @return int
     */
    public function get_wallet($room_id){
        $cache_data = Redis::HGET($this->redis_cache_finance_room_wallet, $room_id);
        if (!empty($cache_data)){
            $data = json_decode($cache_data, true);
            return $data['wealth_balance'];
        }
        $result = DB::table($this->table)
            ->where(['room_id'=>$room_id])
            ->first(['wealth_balance']);
        if (empty($result)){
            return 0;
        }
        $data = self::objToArray($result);
        Redis::HSET($this->redis_cache_finance_room_wallet, $room_id, json_encode($data));
        return intval($data['wealth_balance']);

//        $result = DB::table('finance_union_room_stream')
//            ->whereIn('data_type', [1, 2])
//            ->selectRaw(DB::raw("SUM(data_value * data_num) as total "))
//            ->where('room_id',$room_id)
//            ->first(['total']);
//        if (empty($result)){
//            return 0;
//        }
//        $data = self::objToArray($result);
//        return intval($data['total']);
    }


}